# coding=utf-8
# author:xc
# datetime:2018/8/27 13:42
from app import util, upload_files
from dbConnection.MysqlConn import Mysql
from . import html
from flask import request
import time


# 个人信息
@html.route('/api/person/info', methods=['POST', 'GET'])
@util.verify_login
def api_person_info(uid):
    try:
        mysql = Mysql()
        sql = "select * from girl_teacher where uid='%s'" % uid
        result = mysql.getOne(sql, None)
        mysql.dispose()
        res = {}
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            if not result['header'].startswith('http:'):
                result['header'] = upload_files.baseUrl + result['header']
            res = result
    except Exception as e:
        print e
        code = util.CODE_ERROR
        res = {}
    data = {
        'code': code,
        'res': res
    }
    return util.to_json(data)


# 修改信息
@html.route('/api/update/message', methods=['POST', 'GET'])
@util.verify_login
def api_update_message(uid):
    try:
        nickname = request.values.get('nickname', default="")
        age = request.values.get('age', default=0)
        vocation = request.values.get('vocation', default="")
        sign = request.values.get('sign', default="")
        info = request.values.get('info', default="")
        mysql = Mysql()
        sql = "update girl_teacher set nickname='%s',age='%s',vocation='%s',sign='%s',info='%s'where uid='%s'" % (
            nickname, age, vocation, sign, info, uid)
        result = mysql.update(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        msg = u'修改失败'
        if result > 0:
            code = util.CODE_SUCCESS
            msg = u'修改成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


@html.route('/api/update/header', methods=['POST', 'GET'])
@util.verify_login
def api_update_header(uid):
    try:
        header_file = request.files['file']
        name = str(header_file.filename.split('/')[-1:][0])
        cdn_path = 'header/' + str(int(time.time())) + name
        urls = upload_files.upload_image(header_file, cdn_path, name)
        urls = urls['url']
        mysql = Mysql()
        sql = "update girl_teacher set  header='%s' where uid='%s'" % (urls, uid)
        result = mysql.update(sql, None)
        mysql.dispose()
        code = util.CODE_FAIL
        msg = u'修改失败'
        if result > 0:
            code = util.CODE_SUCCESS
            msg = u'修改成功'
    except Exception as e:
        print e
        code = util.CODE_ERROR
        msg = u'服务器内部错误'
    data = {
        'code': code,
        'msg': msg
    }
    return util.to_json(data)


# 我的帖子
@html.route('/api/mine/poster', methods=['POST', 'GET'])
@util.verify_login
def api_mine_poster(uid):
    try:
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        mysql = Mysql()
        sql = "select a.* from girl_poster as a  where a.status=1  and a.uid='%s'order by a.addTime desc limit %d,%d" % (
            uid, num, util.PAGE_NUM)
        sql2 = "select count(*) from girl_poster  where status=1 and uid='%s'" % uid
        result = mysql.getAll(sql, None)
        count = mysql.getOne(sql2, None)
        mysql.dispose()
        if count:
            count = count['count(*)']
            if count % util.PAGE_NUM > 0:
                max_page = count / util.PAGE_NUM + 1
            else:
                max_page = count / util.PAGE_NUM
        else:
            max_page = 0
        data = []
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                data_poster = dict()
                data_poster['posterId'] = x['posterId']
                data_poster['content'] = x['content']
                data_poster['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data.append(data_poster)
    except Exception as e:
        print  e
        code = util.CODE_ERROR
        data = []
        max_page = 0
    data = {
        'code': code,
        'data': data,
        'max_page': max_page
    }
    return util.to_json(data)


# 帖子详情
@html.route('/api/poster/detail')
@util.verify_login
def api_poster_detail(uid):
    try:
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        posterId = request.values.get('posterId')
        mysql = Mysql()
        sql = "select a.*,b.nickname,b.header,c.praise from girl_poster as a left join " \
              "girl_teacher as b on a.uid= b.uid left join (select * from girl_praise " \
              "where uid='%s') as c on a.posterId=c.posterId where a.status=1 " \
              "and a.posterId='%s' and a.uid='%s' order by a.addTime desc limit %d,%d" % (
                  uid, posterId, uid, num, util.PAGE_NUM)
        sql2 = "select b.*,c.header,c.nickname,d.nickname as name from girl_poster as a " \
               "left join girl_poster_reply as b on a.posterId=b.posterId left join girl_teacher as" \
               " c on b.uid=c.uid left join girl_teacher as d on d.uid=b.f_uid  where " \
               "  b.status=1 and a.posterId='%s' order by b.addTime asc  " % posterId
        result = mysql.getOne(sql, None)
        res = mysql.getAll(sql2, None)
        mysql.dispose()
        code = util.CODE_EMPTY
        data_poster = {}
        if result:
            code = util.CODE_SUCCESS
            data_poster['posterId'] = result['posterId']
            data_poster['flag'] = result['flag']
            data_poster['content'] = result['content']
            if int(result['flag']) == 0:
                data_poster['voiceUrl'] = ""
                data_poster['videoUrl'] = ""
                data_poster['imgUrl'] = ""
            elif int(result['flag']) == 1:
                data_poster['voiceUrl'] = ""
                data_poster['videoUrl'] = ""
                urls = result['imgUrl'].split(',')
                url_list = ''
                for x in urls:
                    if not x.startswith("http"):
                        url_list += upload_files.baseUrl + x + ","
                    else:
                        url_list += x + ","
                url_list = url_list[:-1]
                data_poster['imgUrl'] = url_list
            data_poster['addTime'] = result['addTime'].strftime('%Y-%m-%d %H:%M:%S')
            if result['praise'] is None or int(result['praise']) == 0:
                data_poster['praise'] = 0
            else:
                data_poster['praise'] = 1
            if not result['header'].startswith('http'):
                data_poster['header'] = upload_files + result['header']
            else:
                data_poster['header'] = result['header']
            data_poster['praiseNum'] = result['praiseNum']
            data_poster['nickname'] = result['nickname']
            reply = []
            if res:
                for k in res:
                    if result['posterId'] == k['posterId']:
                        data_reply = dict()
                        data_reply['uid'] = k['uid']
                        data_reply['f_uid'] = k['f_uid']
                        if data_reply['f_uid'] == 0:
                            data_reply['name'] = ""
                        else:
                            data_reply['name'] = k['name']
                        data_reply['content'] = k['content']
                        data_reply['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                        data_reply['nickname'] = k['nickname']
                        if not k['header'].startswith("http"):
                            data_reply['header'] = upload_files.baseUrl + k['header']
                        else:
                            data_reply['header'] = result['header']
                        reply.append(data_reply)
            data_poster['res'] = reply
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data_poster = {}
    data = {
        'data': data_poster,
        'code': code
    }
    return util.to_json(data)

